import {
  Middleware,
  AnyAction,
  Dispatch,
  MiddlewareAPI,
} from '@reduxjs/toolkit';
import { STORAGE, storageSet } from '@fe-hl/shared';
import { IState } from '../types';

const persistenceState: Middleware<unknown, IState> = (
  storeAPI: MiddlewareAPI,
) => {
  return (next: Dispatch<AnyAction>) => {
    return (action: AnyAction) => {
      next(action);
      try {
        const rootState = JSON.stringify(storeAPI.getState(), (key, value) => {
          return key === 'cancelReq' ? undefined : value;
        });
        storageSet('REDUX_PERSISTENCE', JSON.parse(rootState), STORAGE.SESSION);
      } catch (error) {
        console.log(error);
      }
    };
  };
};

export default persistenceState;
